package com.yhy.shiro.test1.login.realm;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

public class MyRealm1 implements Realm {

	
	/**
	 * 返回 realm 名字。名字必须唯一。
	 */
	@Override
	public String getName() {
		return "myrealm1";
	}

	/**
	 * 判断此 Realm 是否支持此 Token
	 */
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

	/**
	 * 根据 Token 获取认证信息
	 */
	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		String pass = new String( (char[])token.getCredentials() );
		
		if( !"zhang".equals(username) ){
			//用户名错误。
			throw new UnknownAccountException();
		}
		
		if( !"123".equals(pass) ){
			//凭证错误
			throw new IncorrectCredentialsException();
		}
		//如果身份验证成功返回一个AuthenticationInfo实现.
		return new SimpleAuthenticationInfo(username, pass,getName() );
	}

}
